<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="源服务器" prop="sourceServerId">
        <el-select v-model="queryParams.sourceServerId" placeholder="请选择源服务器" clearable>
          <el-option
            v-for="item in serverOptions"
            :key="item.serverId"
            :label="item.serverName"
            :value="item.serverId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="目标服务器" prop="targetServerId">
        <el-select v-model="queryParams.targetServerId" placeholder="请选择目标服务器" clearable>
          <el-option
            v-for="item in serverOptions"
            :key="item.serverId"
            :label="item.serverName"
            :value="item.serverId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="任务状态" clearable>
          <el-option
            v-for="dict in dict.type.sync_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['datasync:filesync:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['datasync:filesync:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['datasync:filesync:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="runDisabled"
          @click="handleRun"
          v-hasPermi="['datasync:filesync:run']"
        >执行同步</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['datasync:filesync:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileSyncList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="taskId" width="80" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="源服务器" align="center" prop="sourceServerName" />
      <el-table-column label="源目录" align="center" prop="sourcePath" />
      <el-table-column label="目标服务器" align="center" prop="targetServerName" />
      <el-table-column label="目标目录" align="center" prop="targetPath" />
      <el-table-column label="上次执行时间" align="center" prop="lastRunTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastRunTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sync_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['datasync:filesync:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datasync:filesync:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleRun(scope.row)"
            v-hasPermi="['datasync:filesync:run']"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLog(scope.row)"
            v-hasPermi="['datasync:filesync:log']"
          >日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件同步对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="源服务器" prop="sourceServerId">
              <el-select v-model="form.sourceServerId" placeholder="请选择源服务器">
                <el-option
                  v-for="item in serverOptions"
                  :key="item.serverId"
                  :label="item.serverName"
                  :value="item.serverId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="源目录" prop="sourcePath">
              <el-input v-model="form.sourcePath" placeholder="请输入源目录路径">
                <el-button slot="append" icon="el-icon-folder-opened" @click="openFileBrowser('source')">浏览</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="目标服务器" prop="targetServerId">
              <el-select v-model="form.targetServerId" placeholder="请选择目标服务器">
                <el-option
                  v-for="item in serverOptions"
                  :key="item.serverId"
                  :label="item.serverName"
                  :value="item.serverId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标目录" prop="targetPath">
              <el-input v-model="form.targetPath" placeholder="请输入目标目录路径">
                <el-button slot="append" icon="el-icon-folder-opened" @click="openFileBrowser('target')">浏览</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="文件类型" prop="fileTypes">
          <el-input v-model="form.fileTypes" placeholder="请输入文件类型，多个用逗号分隔，例如：txt,doc,xlsx" />
          <span class="help-block">留空则同步所有文件类型</span>
        </el-form-item>
        <el-form-item label="同步方式" prop="syncMode">
          <el-radio-group v-model="form.syncMode">
            <el-radio
              v-for="dict in dict.type.sync_mode"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执行周期" prop="execCycle">
          <el-radio-group v-model="form.execCycle" @change="handleCycleChange">
            <el-radio label="daily">每天</el-radio>
            <el-radio label="weekly">每周</el-radio>
            <el-radio label="monthly">每月</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="执行时间" prop="execTime">
              <el-time-picker
                v-model="execTimeValue"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择时间"
                @change="handleTimeChange"
              ></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.execCycle === 'weekly'">
            <el-form-item label="星期" prop="weekDay">
              <el-select v-model="form.weekDay" placeholder="选择星期">
                <el-option label="星期一" value="1"></el-option>
                <el-option label="星期二" value="2"></el-option>
                <el-option label="星期三" value="3"></el-option>
                <el-option label="星期四" value="4"></el-option>
                <el-option label="星期五" value="5"></el-option>
                <el-option label="星期六" value="6"></el-option>
                <el-option label="星期日" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.execCycle === 'monthly'">
            <el-form-item label="日期" prop="monthDay">
              <el-select v-model="form.monthDay" placeholder="选择日期">
                <el-option
                  v-for="day in 31"
                  :key="day"
                  :label="`${day}号`"
                  :value="day"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="定时规则预览">
          <el-input v-model="cronPreview" placeholder="自动生成的Cron表达式" readonly>
            <template slot="prepend">Cron表达式</template>
          </el-input>
          <div class="help-block">
            <p>{{ scheduleDescription }}</p>
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sync_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 日志查看对话框 -->
    <el-dialog title="同步日志" :visible.sync="logOpen" width="900px" append-to-body>
      <el-table v-loading="logLoading" :data="logList">
        <el-table-column label="序号" align="center" prop="logId" width="80" />
        <el-table-column label="任务名称" align="center" prop="taskName" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文件数量" align="center" prop="fileCount" width="100" />
        <el-table-column label="总大小" align="center" width="120">
          <template slot-scope="scope">
            <span>{{ formatFileSize(scope.row.totalSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="耗时(秒)" align="center" prop="duration" width="100" />
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.job_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-col :span="24">
          <el-form>
            <el-form-item label="日志详情" style="margin-top: 15px;">
              <el-input
                type="textarea"
                v-model="logDetail"
                :rows="10"
                readonly
              />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 文件浏览器对话框 -->
    <el-dialog :title="fileBrowserTitle" :visible.sync="fileBrowserVisible" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="18">
          <el-input
            placeholder="当前路径"
            v-model="currentPath"
            readonly
          >
            <el-button slot="append" icon="el-icon-back" @click="navigateUp"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button
            type="primary"
            plain
            icon="el-icon-refresh"
            size="small"
            @click="refreshFiles"
          >刷新</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="fileLoading" :data="fileList" style="width: 100%">
        <el-table-column label="" width="40">
          <template slot-scope="scope">
            <i class="el-icon-folder" v-if="scope.row.isDirectory"></i>
            <i class="el-icon-document" v-else></i>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称">
          <template slot-scope="scope">
            <el-link
              type="primary"
              :underline="false"
              v-if="scope.row.isDirectory"
              @click="navigateToDirectory(scope.row.path)">
              {{ scope.row.name }}
            </el-link>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.isDirectory"
              size="mini"
              type="primary"
              @click="selectDirectory(scope.row.path)">选择此目录</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="selectCurrentDirectory">选择当前目录</el-button>
        <el-button @click="fileBrowserVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFileSync, getFileSync, delFileSync, addFileSync, updateFileSync, runFileSync, listSyncLogs, getSyncLogDetail } from "@/api/datasync/filesync";
import { listServerOptions, listServerFiles } from "@/api/datasync/server";

export default {
  name: "FileSync",
  dicts: ['sync_status', 'sync_mode', 'job_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 执行按钮禁用
      runDisabled: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件同步表格数据
      fileSyncList: [],
      // 服务器选项
      serverOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日志弹出层
      logOpen: false,
      // 日志加载层
      logLoading: false,
      // 日志列表
      logList: [],
      // 日志详情
      logDetail: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        sourceServerId: null,
        targetServerId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        sourceServerId: [
          { required: true, message: "源服务器不能为空", trigger: "change" }
        ],
        sourcePath: [
          { required: true, message: "源目录不能为空", trigger: "blur" }
        ],
        targetServerId: [
          { required: true, message: "目标服务器不能为空", trigger: "change" }
        ],
        targetPath: [
          { required: true, message: "目标目录不能为空", trigger: "blur" }
        ],
        syncMode: [
          { required: true, message: "同步方式不能为空", trigger: "change" }
        ],
        execCycle: [
          { required: true, message: "执行周期不能为空", trigger: "change" }
        ],
        execTime: [
          { required: true, message: "执行时间不能为空", trigger: "change" }
        ],
        weekDay: [
          { required: true, message: "星期不能为空", trigger: "change" }
        ],
        monthDay: [
          { required: true, message: "日期不能为空", trigger: "change" }
        ]
      },
      // 执行时间值
      execTimeValue: null,
      // 文件浏览器相关
      fileBrowserVisible: false,
      fileBrowserTitle: "选择目录",
      fileBrowserType: "source", // 'source' 或 'target'
      currentPath: "/",
      fileList: [],
      fileLoading: false,
    };
  },
  computed: {
    // Cron表达式预览
    cronPreview() {
      return this.generateCronExpression();
    },
    // 调度描述
    scheduleDescription() {
      return this.getScheduleDescription();
    }
  },
  created() {
    this.getList();
    this.getServerOptions();
  },
  methods: {
    /** 查询文件同步列表 */
    getList() {
      this.loading = true;
      listFileSync(this.queryParams).then(response => {
        this.fileSyncList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取服务器选项 */
    getServerOptions() {
      listServerOptions().then(response => {
        this.serverOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        taskName: null,
        sourceServerId: null,
        sourcePath: null,
        targetServerId: null,
        targetPath: null,
        fileTypes: null,
        syncMode: "1",
        execCycle: "daily",
        execTime: null,
        weekDay: "1",
        monthDay: 1,
        cronExpression: null,
        status: "0",
        remark: null
      };
      this.execTimeValue = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.runDisabled = selection.length !== 1;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件同步任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskId = row.taskId || this.ids[0];
      getFileSync(taskId).then(response => {
        this.form = response.data;

        // 解析Cron表达式到简化配置
        this.parseCronExpression(this.form.cronExpression);

        this.open = true;
        this.title = "修改文件同步任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 生成Cron表达式
          this.form.cronExpression = this.generateCronExpression();

          if (this.form.taskId != null) {
            updateFileSync(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFileSync(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal.confirm('是否确认删除文件同步任务编号为"' + taskIds + '"的数据项？').then(function() {
        return delFileSync(taskIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 执行周期变化 */
    handleCycleChange() {
      // 周期变化时重新生成Cron表达式
      this.form.cronExpression = this.generateCronExpression();
    },

    /** 执行时间变化 */
    handleTimeChange(time) {
      this.form.execTime = time;
      this.form.cronExpression = this.generateCronExpression();
    },

    /** 生成Cron表达式 */
    generateCronExpression() {
      if (!this.form.execTime) {
        return "";
      }

      const timeParts = this.form.execTime.split(":");
      const hour = timeParts[0];
      const minute = timeParts[1];

      let cronExpression = "";

      switch (this.form.execCycle) {
        case "daily":
          // 每天执行：0 分 时 * * ?
          cronExpression = `0 ${minute} ${hour} * * ?`;
          break;
        case "weekly":
          // 每周执行：0 分 时 ? * 周
          const weekDay = this.form.weekDay || "1";
          cronExpression = `0 ${minute} ${hour} ? * ${weekDay}`;
          break;
        case "monthly":
          // 每月执行：0 分 时 日 * ?
          const monthDay = this.form.monthDay || "1";
          cronExpression = `0 ${minute} ${hour} ${monthDay} * ?`;
          break;
        default:
          cronExpression = `0 ${minute} ${hour} * * ?`;
      }

      return cronExpression;
    },

    /** 获取调度描述 */
    getScheduleDescription() {
      if (!this.form.execTime) {
        return "请选择执行时间";
      }

      const time = this.form.execTime;
      let description = "";

      switch (this.form.execCycle) {
        case "daily":
          description = `每天 ${time} 执行`;
          break;
        case "weekly":
          const weekDays = {
            "0": "星期日",
            "1": "星期一",
            "2": "星期二",
            "3": "星期三",
            "4": "星期四",
            "5": "星期五",
            "6": "星期六"
          };
          const weekDay = weekDays[this.form.weekDay] || "星期一";
          description = `每周${weekDay} ${time} 执行`;
          break;
        case "monthly":
          const monthDay = this.form.monthDay || 1;
          description = `每月${monthDay}号 ${time} 执行`;
          break;
        default:
          description = `每天 ${time} 执行`;
      }

      return description;
    },

    /** 解析Cron表达式 */
    parseCronExpression(cronExpression) {
      if (!cronExpression) {
        return;
      }

      try {
        const parts = cronExpression.split(" ");
        if (parts.length >= 6) {
          const second = parts[0];
          const minute = parts[1];
          const hour = parts[2];
          const day = parts[3];
          const month = parts[4];
          const week = parts[5];

          // 设置时间
          this.form.execTime = `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
          this.execTimeValue = this.form.execTime;

          // 判断执行周期
          if (week !== "?" && week !== "*") {
            // 每周执行
            this.form.execCycle = "weekly";
            this.form.weekDay = week;
          } else if (day !== "*" && day !== "?") {
            // 每月执行
            this.form.execCycle = "monthly";
            this.form.monthDay = parseInt(day);
          } else {
            // 每天执行
            this.form.execCycle = "daily";
          }
        }
      } catch (error) {
        console.warn("解析Cron表达式失败:", error);
        // 默认设置
        this.form.execCycle = "daily";
        this.form.execTime = "00:00";
        this.execTimeValue = "00:00";
      }
    },
    /** 执行同步按钮操作 */
    handleRun(row) {
      const taskId = row.taskId || this.ids[0];
      this.$modal.confirm('是否确认立即执行该同步任务？').then(function() {
        return runFileSync(taskId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("任务执行中，请稍后查看执行结果");
      }).catch(() => {});
    },
    /** 查看日志按钮操作 */
    handleLog(row) {
      this.logOpen = true;
      this.logLoading = true;
      this.logDetail = "";
      listSyncLogs(row.taskId).then(response => {
        this.logList = response.data;
        this.logLoading = false;
        
        // 默认展示第一条日志详情
        if (this.logList.length > 0) {
          this.showLogDetail(this.logList[0].logId);
        }
      });
    },
    /** 显示日志详情 */
    showLogDetail(logId) {
      getSyncLogDetail(logId).then(response => {
        this.logDetail = response.data;
      });
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (!size) return '0 B';
      
      size = Number(size);
      if (size < 1024) {
        return size + ' B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB';
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + ' MB';
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datasync/filesync/export', {
        ...this.queryParams
      }, `filesync_${new Date().getTime()}.xlsx`);
    },
    // 打开文件浏览器
    openFileBrowser(type) {
      if (type === 'source' && !this.form.sourceServerId) {
        this.$message.error('请先选择源服务器');
        return;
      }
      if (type === 'target' && !this.form.targetServerId) {
        this.$message.error('请先选择目标服务器');
        return;
      }

      this.fileBrowserType = type;
      this.fileBrowserTitle = type === 'source' ? '选择源目录' : '选择目标目录';
      this.currentPath = type === 'source' ? (this.form.sourcePath || '/') : (this.form.targetPath || '/');
      this.fileList = [];
      this.fileBrowserVisible = true;
      this.loadDirectoryContents(this.currentPath);
    },

    // 刷新文件列表
    refreshFiles() {
      this.loadDirectoryContents(this.currentPath);
    },

    // 加载目录内容
    loadDirectoryContents(dirPath) {
      this.fileLoading = true;
      const serverId = this.fileBrowserType === 'source' ? this.form.sourceServerId : this.form.targetServerId;
      listServerFiles(serverId, dirPath).then(response => {
        this.fileLoading = false;
        if (response.code === 200) {
          this.fileList = response.data;
          this.currentPath = dirPath;
        } else {
          this.$message.error('加载目录内容失败: ' + response.msg);
        }
      }).catch(() => {
        this.fileLoading = false;
      });
    },

    // 导航到指定目录
    navigateToDirectory(dirPath) {
      this.loadDirectoryContents(dirPath);
    },

    // 导航到上一级目录
    navigateUp() {
      if (this.currentPath === '/' || this.currentPath === '') {
        return;
      }
      const parts = this.currentPath.split('/');
      parts.pop(); // 移除最后一个路径部分
      const parentPath = parts.join('/') || '/';
      this.loadDirectoryContents(parentPath);
    },

    // 选择当前目录
    selectCurrentDirectory() {
      this.selectDirectory(this.currentPath);
    },

    // 选择目录
    selectDirectory(dirPath) {
      if (this.fileBrowserType === 'source') {
        this.form.sourcePath = dirPath;
      } else {
        this.form.targetPath = dirPath;
      }
      this.fileBrowserVisible = false;
    },
  }
};
</script>

<style scoped>
.help-block {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.help-block p {
  margin: 2px 0;
}

.scrollbar {
  max-height: 600px;
  overflow-y: auto;
}
</style>